
package com.xifan.myaccount;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xifan.myaccount.database.DatabaseImpl;
import com.xifan.myaccount.entity.RecordDetail;
import com.xifan.myaccount.util.ImageUtil;
import com.xifan.myaccount.util.SmartType;
import com.xifan.myaccount.util.UiHelper;
import com.xifan.myaccount.widget.MoneyView;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

import java.io.File;
import java.util.HashMap;

public class ShowRecord extends SwipeBackActivity implements
        DialogInterface.OnClickListener {

    private Context mContext;

    private MoneyView mMoneyView;
    private TextView mDateText;
    private TextView mTypeText;
    private TextView mLocationText;
    private TextView mNoteText;
    private ImageView mBgView;
    private TextView mTipText;
    private RelativeLayout mBottomView;

    private RecordDetail mDetail;

    private File mPicPath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_record);
        mContext = this;
        mDetail = getIntent().getParcelableExtra("detail");

        getActionBar().setDisplayHomeAsUpEnabled(true);

        initView();
    }

    private void initView() {
        mBottomView = (RelativeLayout) findViewById(R.id.details);
        mMoneyView = (MoneyView) findViewById(R.id.details_money);
        mDateText = (TextView) findViewById(R.id.details_date);
        mTypeText = (TextView) findViewById(R.id.details_type);
        mLocationText = (TextView) findViewById(R.id.details_location);
        mNoteText = (TextView) findViewById(R.id.details_note);
        mBgView = (ImageView) findViewById(R.id.background);
        mTipText = (TextView) findViewById(R.id.details_add_tip);
        mTipText.setOnLongClickListener(new OnLongClickListener() {
            public boolean onLongClick(View v) {
                String[] items = mPicPath == null ? getResources().getStringArray(
                        R.array.choose_pic_source) : getResources().getStringArray(
                        R.array.choose_pic_source_exists);
                UiHelper.createPhotoDialog(mContext, items, ShowRecord.this).show();
                return true;
            }
        });
        mBottomView.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AddRecord.class);
                intent.putExtra("detail", mDetail);
                startActivityForResult(intent, UiHelper.START_EDIT_RECORD);
            }
        });

        updateView();
    }

    private void updateView() {
        mTypeText.setText(SmartType.getTypeInfoById(mDetail.getRecordType()).typeName);
        mMoneyView.setText(mDetail.getMoney());
        mDateText.setText(mDetail.getDate());
        mLocationText.setText(mDetail.getLocation());
        mNoteText.setText(mDetail.getNote());
        if (!TextUtils.isEmpty(mDetail.getPicUri())) {
            Bitmap bmp = BitmapFactory.decodeFile(mDetail.getPicUri());
            mBgView.setImageBitmap(bmp);
            mPicPath = new File(mDetail.getPicUri());
        } else {
            mBgView.setImageDrawable(null);
            mPicPath = null;
        }
        // Leave the text blank to show space in layout.
        mTipText.setText(mBgView.getDrawable() == null ? getString(R.string.show_record_add_pic)
                : " ");

    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case UiHelper.REQUEST_SELECT_CAMERA:
                // init storage path
                mPicPath = ImageUtil.getDefaultPicPath();
                Intent i = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPicPath));
                startActivityForResult(i, UiHelper.REQUEST_SELECT_CAMERA);
                break;
            case UiHelper.REQUEST_SELECT_PICTURE:
                Intent intent = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, UiHelper.REQUEST_SELECT_PICTURE);
                break;
            case UiHelper.REQUEST_SELECT_NONE:
                mPicPath = null;
                savePics();
                updateView();
                break;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UiHelper.START_EDIT_RECORD) {
            if (resultCode == -1) {
                mDetail = data.getParcelableExtra("detail");
                updateView();
                setResult(RESULT_OK);
            }
        } else {
            if (resultCode == -1) {
                // init storage path
                mPicPath = ImageUtil.getDefaultPicPath();

                CropTask cropTask = new CropTask();
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("action", requestCode);
                map.put("data", data);
                cropTask.execute(map);
                Toast.makeText(mContext, getResources().getString(R.string.msg_loading),
                        Toast.LENGTH_SHORT).show();
            } else {
                // issues when no pic in detail and get pic failed,picPath will
                // get a error path
                // so keep it null.
                if (mDetail.getPicUri().equals("") && mPicPath != null)
                    mPicPath = null;
                Toast.makeText(mContext,
                        getResources().getString(R.string.show_record_choose_pic_failed),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private class CropTask extends AsyncTask<HashMap<String, Object>, Void, Bitmap> {
        protected Bitmap doInBackground(HashMap<String, Object>... params) {
            int requestCode = (Integer) params[0].get("action");
            Intent data = (Intent) params[0].get("data");
            Bitmap bitmap = null;
            if (requestCode == UiHelper.REQUEST_SELECT_PICTURE) {
                bitmap = ImageUtil.getPicFromAlbum(mContext, mPicPath, data.getData());
            } else if (requestCode == UiHelper.REQUEST_SELECT_CAMERA) {
                bitmap = ImageUtil.getPicFromCamera(mContext, mPicPath);
            }
            return bitmap;
        }

        protected void onPostExecute(Bitmap bitmap) {
            // super.onPostExecute(bitmap);
            mBgView.setImageBitmap(bitmap);
            savePics();
            updateView();
        }
    }

    private void savePics() {
        mDetail.setPicUri(mPicPath != null ? mPicPath.getPath() : "");
        DatabaseImpl db = new DatabaseImpl(mContext);
        ContentValues cv = new ContentValues();
        cv.put("picUri", mDetail.getPicUri());
        db.doUpdate(DatabaseImpl.DB_TABLE_DETAIL, cv, "id=?", new String[] {
                String.valueOf(mDetail.getId())
        });
        setResult(RESULT_OK);
    }

}
